#include<iostream>
#include<assert.h>
#include<vector>
#include<string>

using namespace std;

//strstr模拟实现
char* my_strstr(char* str1, const char* str2)
{
	assert(str1 && str2);

	char* s1 = str1;
	char* s2 = (char*)str2;
	char* p = s1;

	while (*p)
	{
		s1 = p;
		s2 = (char*)str2;

		while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
		{
			s1++;
			s2++;
		}
		if (*s2 == '\0')
		{
			return (char*)p;
		}
		p++;
	}

	return NULL;
}

void test_strstr()
{
	char a[] = "abcdef";

	const char* b = "abck";
	if (my_strstr(a, b))
		cout << my_strstr(a, b) << endl;
	else
		cout << "找不到子串" << endl;

}


//memcpy模拟实现

void* my_memcpy(void* dest, const void* sorc, size_t n)
{
	assert(dest && sorc);
	void* p = dest;

	while (n--)
	{
		*(char*)dest = *(char*)sorc;
		dest = (char*)dest + 1;
		sorc = (char*)sorc + 1;

	}

	return p;
}

void test_memcpy()
{
	int arr1[] = { 0,1,2,3,4,5,6,7,8,9 };
	int arr2[50] = { 0 };
	my_memcpy(arr2, arr1, sizeof(arr1));
	int i = 0;
	for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
	{
		printf("%d ", arr2[i]);
	}
	printf("\n");
	printf("\n");

}


//memmove的实现
void* my_memmove(void* dest, const void* sorc, size_t n)
{
	assert(dest && sorc);

	void* p = dest;

	//从前向后拷贝
	if (dest < sorc)
	{

		while (n--)
		{
			*(char*)dest = *(char*)sorc;
			dest = (char*)dest + 1;
			sorc = (char*)sorc + 1;

		}
	}
	//从后向前拷贝
	else
	{
		while (n--)
		{
			*((char*)dest + n) = *((char*)sorc + n);
		}
	}

	return p;
}


void test_mymemmove()
{
	int arr1[] = { 1,2,3,4,5,6,7,8,9 };
	my_memmove(arr1 + 2, arr1, 20);
	int i = 0;
	for (i = 0; i < 9; i++)
	{
		printf("%d ", arr1[i]);
	}
	printf("\n");
	printf("\n");

}

int main()
{
	test_strstr();

	test_memcpy();

	test_mymemmove();

    return 0;
}
